<template>
  <template v-if="field.group === 'layout'">
    <FormControl :isLayout="true" :isSelected="isSelected" @copyControl="copyControl" @deleteControl="deleteControl">
      <template v-if="field.type === 'grid'">
        <el-row :gutter="field.attrs.gutter">
          <el-col v-for="(el, index) in field.attrs.cols" :span="span(index)">
            <FormItemNested v-model="formItemList[index]" :isSelectedControl="isSelectedControl"
              @copyControlGroup="copyControlGroup" @clickControlGroup="clickControlGroup" />
          </el-col>
        </el-row>
      </template>
    </FormControl>
  </template>
  <template v-else>
    <FormControl :isLayout="false" :isSelected="isSelected" @copyControl="copyControl" @deleteControl="deleteControl">
      <FormItem class="custom-item" :field="field" :key="field.id" :data="{}" />
    </FormControl>
  </template>
</template>

<script setup lang="ts">
import { uniqueId } from 'lodash';
import { FormGroup, gridLayout } from '../..';

const isSelectedControl = defineModel<FormGroup>('isSelectedControl');

const field = defineModel<FormGroup>('field');

const isSelected = computed(() => {
  return isSelectedControl.value.id === field.value.id;
})

// grid布局列数发生变化时处理
const formItemList = computed(() => {
  const cols = field.value.attrs.cols;
  const length = field.value.formItemList.length;
  if (cols != length) {
    field.value.attrs.layout = 1;
    if (cols > length) {
      for (let i = 0; i < cols - length; i++) {
        field.value.formItemList.push({
          id: uniqueId(),
          group: field.value.group,
          type: field.value.type,
          formItemList: []
        })
      }
    } else {
      for (let i = 0; i < length - cols; i++) {
        field.value.formItemList.pop();
      }
    }
  }

  return field.value.formItemList;
})

const span = (index: number) => {
  const col = gridLayout.find(x => x.cols === field.value.attrs.cols).rows;
  const row = col.find(x => x.id === field.value.attrs.layout) || col[0];
  const cols = row.values.reduce((acc, curr) => acc + curr, 0);
  return row.values[index] * 24 / cols;
}

const emits = defineEmits(["copyControl", "copyControlGroup", "deleteControl", "clickControlGroup"]);

const copyControlGroup = (field: FormGroup) => {
  emits("copyControlGroup", field);
}

const clickControlGroup = (field: FormGroup) => {
  emits("clickControlGroup", field);
}

const copyControl = () => {
  emits("copyControl", field);
};

const deleteControl = () => {
  emits("deleteControl", field);
};

</script>

<style lang="scss" scoped>
.custom-item {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
